﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RWLibrary.Util;
namespace RWLibrary.Logic.Queries
{
    using Graph;
    public class PossiblyGoalQuery : GoalQuery 
    {
        public PossiblyGoalQuery(Graph graph) : base(graph)
        {
        }

        public override bool Excecute()
        {
            HashSet<Node> visited = new HashSet<Node>();
          
            int maxStateBound = 1 << Graph.World.FluentCount;
            Dictionary<Node, int> notVisited = Graph.Nodes.Where(n => n.IsInitial).ToDictionary(node => node, node => 0);

            while (notVisited.Count > 0)
            {
                var next = notVisited.MinBy(p => p.Value);
                if(Goal.Test(next.Key.State))
                    return true;
                notVisited.Remove(next.Key);
                visited.Add(next.Key);
                foreach (var edge in next.Key.Connections)
                    if (!visited.Contains(edge.Value) && next.Value + edge.Key.Cost <= Cost)
                    {
                        if (!notVisited.ContainsKey(edge.Value))
                            notVisited[edge.Value] = next.Value + edge.Key.Cost;
                        else
                            if (notVisited[edge.Value] > next.Value + edge.Key.Cost)
                                notVisited[edge.Value] = next.Value + edge.Key.Cost;
                    }
                
            }
            return false;
        }
    }
}
